/**
 * 
 */
package com.gomeplus.commons.quartz.factory;

import java.util.Iterator;
import java.util.List;

import com.gomeplus.commons.quartz.job.ExcuteNowTemplate;
import net.sf.json.JSONObject;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import com.gomeplus.commons.quartz.build.TaskBuildSource;
import com.gomeplus.commons.quartz.cache.QuartzConstants;
import com.gomeplus.commons.quartz.cache.QuartzTaskConfigCache;
import com.gomeplus.commons.quartz.netty.NettyMessage;
import com.gomeplus.commons.quartz.netty.client.NettyClientTaskRunLogSend;

/**
 * @author chenmin-ds
 *
 */
public class TaskListenerClientFactory {
	
	private Logger logger = LoggerFactory.getLogger("TaskListenerClientFactory");
	
	private TaskBuildSource taskBuildSourceProxy;
	
	public void setTaskBuildSourceProxy(TaskBuildSource taskBuildSourceProxy) {
		this.taskBuildSourceProxy = taskBuildSourceProxy;
	}

	/**
	 * 接收服务端发过来的信息，并进行业务处理
	 * @param nettyMessage
	 */
	public void businessAdapter(NettyMessage nettyMessage){
		String businessType = nettyMessage.getBusinessType();
		if(QuartzConstants.BUSINESS_TYPE_RWXXCX_INITS.equals(businessType)){
			initsRemoteTask(nettyMessage);
		}else if(QuartzConstants.BUSINESS_TYPE_RWXXCX_UPDATE.equals(businessType)){
			updateRemoteTask(nettyMessage);
		}else if(QuartzConstants.BUSINESS_TYPE_HOLD_ONE.equals(businessType)){
			holdOneTask(nettyMessage);
		}else if(QuartzConstants.TASK_PART_SET.equals(businessType)){
			taskPartSet(nettyMessage);
		}else if(QuartzConstants.TASK_STOP_RUN.equals(businessType)){
			taskStopOrRun(nettyMessage);
		}else if(QuartzConstants.TASK_EXECUTE_ONCE_NOW.equals(businessType)){
			executeOnceNow(nettyMessage);
		}
	}

	/*
	 * 立即执行
	 */
	private void executeOnceNow(NettyMessage nettyMessage){
		try{
			String beanName = String.valueOf(nettyMessage.getJsonObject("businessObjName"));
			new ExcuteNowTemplate().execute(beanName);
		}catch(Exception e){
			logger.error("全局唯一性任务操作异常",e);
		}
	}

	/*
	 * 任务暂停
	 */
	private void taskStopOrRun(NettyMessage nettyMessage){
		try{
			taskBuildSourceProxy.taskStopOrRun(nettyMessage.getJsonObject());
			new NettyClientTaskRunLogSend().sendInfoServer();
		}catch(Exception e){
			logger.error("全局唯一性任务操作异常",e);
		}
	}
	
	/*
	 * 任务分片信息设置
	 * setTypes：true,添加；false,清理
	 */
	private void taskPartSet(NettyMessage nettyMessage){
		try{
			String modeValue = (String) nettyMessage.getJsonObject("modeValue");
			String partValue = (String) nettyMessage.getJsonObject("partValue");
			String setTypes = (String) nettyMessage.getJsonObject("setTypes");
			String objTaskName = (String) nettyMessage.getJsonObject("businessObjName");
			if("true".equals(setTypes)){
				JSONObject runLog = QuartzTaskConfigCache.getTaskRunLog(objTaskName);
				runLog.put("partValue", partValue);
				runLog.put("modeValue", modeValue);
				QuartzTaskConfigCache.setTaskRunLog(objTaskName,runLog);
				QuartzTaskConfigCache.setTaskPart(objTaskName, new String[]{modeValue,partValue});
			}else{
				JSONObject runLog = QuartzTaskConfigCache.getTaskRunLog(objTaskName);
				runLog.put("partValue", "");
				runLog.put("modeValue", "");
				QuartzTaskConfigCache.setTaskRunLog(objTaskName,runLog);
				QuartzTaskConfigCache.clearTaskPart(objTaskName);
			}
			new NettyClientTaskRunLogSend().sendInfoServer();
		}catch(Exception e){
			logger.error("全局唯一性任务操作异常",e);
		}
	}
	
	/*
	 * 全局唯一性任务操作
	 */
	private void holdOneTask(NettyMessage nettyMessage){
		try{
			JSONObject jsonObject = (JSONObject) nettyMessage.getJsonObject(QuartzConstants.BUSINESS_TYPE_HOLD_ONE);
			String oneTaskRunType = (String) nettyMessage.getJsonObject("oneTaskRunType");
			taskBuildSourceProxy.oneTask(jsonObject,oneTaskRunType);
			new NettyClientTaskRunLogSend().sendInfoServer();
		}catch(Exception e){
			logger.error("全局唯一性任务操作异常",e);
		}
	}

	/*
	 * 任务初始化
	 */
	@SuppressWarnings("unchecked")
	private void initsRemoteTask(NettyMessage nettyMessage){
		try{
			List<JSONObject> list = (List<JSONObject>) nettyMessage.getJsonObject(QuartzConstants.TASK_CONFIG_INFO_ARRAYS);
			for(JSONObject object : list){
				taskBuildSourceProxy.initsTask(object);
				QuartzTaskConfigCache.setTaskInfo(object.getString("taskNo"), object);
			}
		}catch(Exception e){
			logger.error("任务链初始化工厂执行任务变更异常",e);
		}
	}
	
	/*
	 * 任务信息更新
	 */
	@SuppressWarnings("unchecked")
	private void updateRemoteTask(NettyMessage nettyMessage){
		try{
			List<JSONObject> list = (List<JSONObject>) nettyMessage.getJsonObject(QuartzConstants.TASK_CONFIG_INFO_ARRAYS);
			JSONObject oldValue = null;
			for (Iterator<JSONObject> it = list.iterator(); it.hasNext();){
				JSONObject object = it.next();
				oldValue = QuartzTaskConfigCache.getTaskInfo(object.getString("taskNo"));
				if(null != oldValue && !QuartzTaskConfigCache.checkUpdate(object)){
					it.remove();
					continue;
				}
				taskBuildSourceProxy.updateTask(object);
				QuartzTaskConfigCache.setTaskInfo(object.getString("taskNo"), object);
			}
		}catch(Exception e){
			logger.error("任务链变更工厂执行任务变更异常",e);
		}
	}
}
